//
//  Common.swift
//  Auscultation
//
//  Created by zwb on 2021/3/22.
//

import Foundation
import UIKit

public func changeFontColor(totalString: String, subString: String, font: UIFont, textColor: UIColor)-> NSMutableAttributedString {
    let attributedString = NSMutableAttributedString(string: totalString)
    let mainStr = NSString(string: totalString)
    let loc:Int  = mainStr.range(of: subString).location
    let len = subString.count
    attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: textColor, range: NSMakeRange(loc, len))
    attributedString.addAttribute(NSAttributedString.Key.font, value: font, range: NSMakeRange(loc, len))
    return attributedString
}


/// GCD定时器倒计时
///
/// - Parameters:
///   - timeInterval: 间隔时间
///   - repeatCount: 重复次数
///   - handler: 循环事件,闭包参数: 1.timer 2.剩余执行次数
public func dispatchTimer(timeInterval: Double, repeatCount: Int, handler: @escaping (DispatchSourceTimer?, Int) -> Void) -> DispatchSourceTimer? {
    
    if repeatCount <= 0 {
        return nil
    }
    let timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
    var count = repeatCount
    timer.schedule(deadline: .now(), repeating: timeInterval)
    timer.setEventHandler {
        count -= 1
        DispatchQueue.main.async {
            handler(timer, count)
        }
        if count == 0 {
            timer.cancel()
        }
    }
    timer.resume()
    return timer
}


func dateNowAsString() -> String {
    let nowDate = Date()
    let formatter = DateFormatter()
    let zone = NSTimeZone.system
    let interval = zone.secondsFromGMT()
    let now = nowDate.addingTimeInterval(TimeInterval(interval))
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let date = formatter.string(from: now)
    return date
}


public func secondsToFormat(seconds:Int) ->  String {
    var hour = 0
    var min = 0
    var second = 0
    var result = ""
    if (seconds>60) {   //是否大于零
        min = seconds/60;  //分钟
        second = seconds%60;  //秒
        if (min>60) {   //存在时
            hour=min/60;
            min=min%60;
        }
    }else{
        second = seconds
    }
    if (hour>0) {
        result=hour.string+"小时";
    }
    if (min>0) {
        result=result+min.string+"分";
    }else if (min==0&&hour>0) {  //当分为0时,但是时有值,所以要显示,避免出现2时0秒现象
        result=result+min.string+"分";
    }
    
    result=result+second.string+"秒";   //秒必须出现无论是否大于零

    return result
}


func loadXibView<T: UIView>(withClass name: T.Type) -> T {
    let views = Bundle.main.loadNibNamed(String(describing: name), owner: nil, options: nil)
    let view:T = views![0]  as! T
    return view
}

